class CommGroup extends React.Component {
    constructor(props) {
        super(props);
        this.commList = [];
        this.state = {
            commGroupList: '',
            commList: '',
            groupName: '',
            currentGroupCommList: ''
        }
    }

    layuiInitComplete() {
        this.form = layui.form();
        this.element = layui.element();
        this.form.on('select(selectGroup)', function (data) {
            this.selectCommInfoSuccess();
        }.bind(this));

        this.form.on('select(distributionMode)', (data) => {
            if (data.value === "DIS_GROUP_TYPE") {
                this.queryCommGroup();
            } else {
                this.setState({}, () => {
                    console.log(this.refs.buildingSelectList);
                    this.refs.buildingSelectList.queryList();
                })
            }
        });

        this.form.on('checkbox(checkboxComm)', function (data) {
            let checkboxElem = data.elem;
            let isChecked = checkboxElem.checked;
            let commCode = data.value;
            let param = {};
            param.commCode = commCode;
            param.groupId = this.refs.groupId.value;
            postJson("/CommGroupCtrl/isGroup.x", $.param(param), function (data) {
                let ret = data.data;
                if (isChecked && ret.isGroup) {
                    checkboxElem.checked = false;
                    this.form.render('checkbox');
                    let comms = this.state.commList;
                    for (let i in comms) {
                        if (commCode === comms[i].comm_code) {
                            let str = "小区 <span style='color: #0c91e5'>【" + commCode + "】" + comms[i].comm_name + "</span>&nbsp;&nbsp;已被组:<br/>";
                            for (let j in ret.commGroupList) {
                                // noinspection JSUnfilteredForInLoop
                                str += "【" + ret.commGroupList[j].groupName + "】<br/>"
                            }
                            str += "绑定，你确定要绑定到多个组吗？";
                            let index = layer.confirm(str,
                                {
                                    btn: ['确定', '取消'] //按钮
                                }, () => {
                                    this.checkboxCommList(commCode, isChecked);
                                    checkboxElem.checked = true;
                                    this.form.render('checkbox');
                                    layer.close(index);
                                }, () => {
                                });
                            break;
                        }
                    }
                } else {
                    this.checkboxCommList(commCode, isChecked);
                }
            }.bind(this));
        }.bind(this));
        this.refs.buildingSelectList.layuiInitComplete();
        this.refs.buildingSelectList.queryList();
    }

    getcurrentCommInfo() {
        return {
            commCode: this.refs.distributionMode &&
            this.refs.distributionMode.value === "DIS_COMM_TYPE" &&
            this.refs.buildingSelectList &&
            this.refs.buildingSelectList.getDefCommCode() !== "-1" ? this.refs.buildingSelectList.getDefCommCode() : null,
            commGroupId: this.refs.distributionMode &&
            this.refs.distributionMode.value === "DIS_GROUP_TYPE" &&
            this.refs.selectGroup &&
            this.refs.selectGroup.value !== "-1" ? this.refs.selectGroup.value : null
        };
    }

    getcurrentGroupCommList() {
        return this.state.currentGroupCommList;
    }

    checkboxCommList(commCode, isChecked) {
        let j = -1;
        for (let i in this.commList) {
            if (this.commList[i] === commCode) {
                j = i;
                break;
            }
        }

        if (isChecked) {
            if (j === -1) {
                this.commList.push(commCode);
            }
        } else {
            if (j !== -1) {
                this.commList.splice(j, 1);
            }
        }
    }

    selectCommInfoSuccess() {
        let commInfo = this.getcurrentCommInfo();
        if (this.props.selectCommInfoCallback) {
            this.props.selectCommInfoCallback(commInfo);
        }
        if (!commInfo.commGroupId) {
            this.setState({
                currentGroupCommList: ''
            });
            return;
        }
        let param = {};
        param.isCommInfo = true;
        param.parentGroupId = commInfo.commGroupId;
        postJson("/CommGroupCtrl/queryCommGroupInfo.x", $.param(param), function (data) {
            this.setState({
                currentGroupCommList: data.list
            });
        }.bind(this));
    }

    queryCommGroup() {
        let param = {};
        param.isPage = false;
        postJson("/CommGroupCtrl/queryCommGroup.x", $.param(param), function (data) {
            this.setState({
                commGroupList: data.list
            }, function () {
                this.form.render('select');
                this.selectCommInfoSuccess();
                this.element.init();
            });
        }.bind(this));
    }

    selectCallback() {
        this.selectCommInfoSuccess();
    }

    checkboxCommView(commCode) {
        if (this.commList.length > 0) {
            for (let i in this.commList) {
                if (this.commList[i] === commCode) {
                    return (<input type="checkbox" name="checkboxComm" data-filter="checkboxComm"
                                   checked={true} value={commCode}/>)
                }
            }
        }
        return (<input type="checkbox" name="checkboxComm" data-filter="checkboxComm"
                       checked={false} value={commCode}/>);
    }

    commTbody() {
        if (this.state.commList) {
            return this.state.commList.map(function (array) {
                if (this.props.isAdmin) {
                    if (array.comm_code === '0000') {
                        return (<tr>
                            <td>{array.comm_code}</td>
                            <td>{array.comm_name}</td>
                            <td>
                                {this.checkboxCommView(array.comm_code)}
                            </td>
                        </tr>)
                    }
                } else {
                    return (<tr>
                        <td>{array.comm_code}</td>
                        <td>{array.comm_name}</td>
                        <td>
                            {this.checkboxCommView(array.comm_code)}
                        </td>
                    </tr>)
                }
            }.bind(this))
        }
    }

    updateCommList(param) {
        postJson('/comm/findCommListPage.x', $.param(param), function (data) {
            this.setState({
                commList: data.list
            }, function () {
                this.form.render('checkbox');
            });
            if (param.page === 1) {
                layui.laypage({
                    cont: 'commSelectListPage'
                    , pages: Math.ceil(data.size / param.pageSize)
                    , jump: function (row, first) {
                        if (!first) {
                            param.page = row.curr;
                            this.updateCommList(param);
                        }
                    }.bind(this)
                });
            }
        }.bind(this))
    }

    editModal(isEdit) {
        //获取小区列表
        let paramComm = {};
        paramComm.pageSize = 5;
        paramComm.page = 1;
        this.commList = [];
        if (isEdit) {
            let groupId = this.refs.selectGroup.value;
            for (let i in this.state.commGroupList) {
                if (groupId === this.state.commGroupList[i].id) {
                    this.refs.groupName.value = this.state.commGroupList[i].group_name;
                    this.refs.groupId.value = this.state.commGroupList[i].id;
                    let param = {};
                    param.parentGroupId = groupId;
                    postJson("/CommGroupCtrl/queryCommGroupInfo.x", $.param(param), function (data) {
                        for (let j in data.list) {
                            this.commList.push(data.list[j].comm_code);
                        }
                        layer.open({
                            type: 1,
                            offset: '100px',
                            area: '60%',
                            title: '选择需要的小区并分组', //不显示标题
                            skin: 'layui-layer-demo',
                            anim: 2,
                            shadeClose: true,
                            content: $('#distribution_modal') //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        });
                        this.updateCommList(paramComm);
                    }.bind(this));
                    break;
                }
            }
        } else {
            this.refs.groupName.value = '';
            this.refs.groupId.value = '';
            layer.open({
                type: 1,
                offset: '100px',
                area: '60%',
                title: '选择需要的小区并分组',
                skin: 'layui-layer-demo',
                anim: 2,
                shadeClose: true,
                content: $('#distribution_modal') //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
            this.updateCommList(paramComm);
        }
    }

    createGroup(commCodes) {
        let groupName = this.refs.groupName.value;
        if (groupName.length <= 2) {
            layer.msg('组名最少两个字符！', {icon: 5});
            return;
        }
        if (commCodes.length <= 0) {
            layer.msg('分组最少存在一个小区！', {icon: 5});
            return;
        }

        let params = {
            groupName: groupName,
            groupId: this.refs.groupId.value,
            commCodes: commCodes.join(','),
        };
        postJson("/CommGroupCtrl/saveCommGroup.x", $.param(params), function (data) {
            this.queryCommGroup();
            parent.layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;分组成功', {icon: 6});
            layer.closeAll();
        }.bind(this));
    }

    deleteGroup(groupId) {
        layer.confirm('确定要删除当前组？', {
            btn: ['确定', '取消']
        }, function () {
            let params = {
                groupId: groupId
            };
            postJson("/CommGroupCtrl/deleteCommGroup.x", $.param(params), function (data) {
                this.queryCommGroup();
                parent.layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;删除成功', {icon: 6});
                layer.closeAll();
            }.bind(this));
        }.bind(this));
    }

    selectGroupView() {
        if (this.state.commGroupList && this.state.commGroupList.length > 0) {
            return this.state.commGroupList.map(function (array) {
                return (<option value={array.id}>{array.group_name}</option>);
            }.bind(this));
        } else {
            return (this.props.isAdmin ? '' : <option value="-1">无</option>);
        }
    }

    currentGroupCommListView() {
        if (this.state.currentGroupCommList) {
            return this.state.currentGroupCommList.map(function (array) {
                return ('❖【' + array.commInfo.commCode + '】' + array.commInfo.commName + '　');
            });
        }
    }

    buttonView() {
        let view = [];
        if (!this.props.isAdmin) {
            view.push(<button style={{marginLeft: '10px'}} type="button" onClick={() => this.editModal(true)}
                              className="layui-btn layui-btn-small">编辑该组
            </button>);
            view.push(<button type="button" onClick={() => this.editModal(false)}
                              className="layui-btn layui-btn-normal layui-btn-small">添加新组
            </button>);
        }
        return view;
    }

    distributionModeView() {
        if (this.refs.distributionMode && this.refs.distributionMode.value === "DIS_GROUP_TYPE") {
            return (<div>
                <label className="layui-form-label" style={{marginLeft: "10px"}}>选择分组</label>
                <div className="layui-input-inline" style={{marginBottom: "1px"}}>
                    <select name="selectGroup" ref="selectGroup" data-filter="selectGroup">
                        {this.selectGroupView()}
                    </select>
                </div>
                {this.buttonView()}
                <div className="layui-collapse" data-filter="test">
                    <div className="layui-colla-item">
                        <h2 className="layui-colla-title">展开查看分组所包含的小区集合</h2>
                        <div className="layui-colla-content">
                            <p>{this.currentGroupCommListView()}</p>
                        </div>
                    </div>
                </div>
            </div>)
        } else {
            return (<BuildingSelectList labelStyle={{marginLeft: "10px"}} ref="buildingSelectList" isNotItem={true}
                                        selectCallback={(commCode) => this.selectCallback(commCode)}/>)
        }
    }

    render() {
        return <div>
            <label className="layui-form-label">分配方式</label>
            <div className="layui-input-inline" style={{float: "left"}}>
                <select name="distributionMode" ref="distributionMode" data-filter="distributionMode">
                    <option value="DIS_COMM_TYPE">按小区分配</option>
                    <option value="DIS_GROUP_TYPE">按小区组分配</option>
                </select>
            </div>
            {this.distributionModeView()}
            <div id="distribution_modal" style={{display: 'none', padding: '10px'}}>
                <input type="hidden" name="groupId" ref="groupId"/>
                <div className="layui-form-item">
                    <label className="layui-form-label">分组名称</label>
                    <div className="layui-input-block">
                        <input name="groupName" ref="groupName" data-verify="groupName" placeholder="请输入分组名称"
                               autoComplete="off" className="layui-input" type="text"/>
                    </div>
                </div>
                <div className="layui-form-item">

                    <div style={{'padding-bottom': '10px'}}>
                        <table className="layui-table" data-skin="line">
                            <colgroup>
                                <col/>
                                <col/>
                                <col width="90"/>
                            </colgroup>
                            <thead>
                            <tr>
                                <th>选择组包含的小区</th>
                                <th/>
                                <th/>
                            </tr>
                            </thead>

                            <tbody>
                            {this.commTbody()}
                            </tbody>
                        </table>

                        <button type="button" onClick={() => this.createGroup(this.commList)}
                                className="layui-btn layui-btn-normal"> 确定
                        </button>

                        {this.refs.groupId && this.refs.groupId.value ?
                            <button type="button" className="layui-btn layui-btn-danger"
                                    onClick={() => this.deleteGroup(this.refs.groupId.value)}>删除</button> : ''}

                        <div style={{'float': 'right', 'margin-right': '1px'}} id="commSelectListPage"/>
                    </div>
                </div>
            </div>
        </div>
    }
}
